package onlinejudge.service.impl;

import onlinejudge.dao.CommentDao;
import onlinejudge.dao.ReplyDao;
import onlinejudge.dao.SolutionCommentDao;
import onlinejudge.dao.UserDao;
import onlinejudge.entity.Comment;
import onlinejudge.entity.Reply;
import onlinejudge.entity.SolutionComment;
import onlinejudge.service.SolutionCommentService;
import onlinejudge.util.DateUtil;
import onlinejudge.vo.CommentVo;
import onlinejudge.vo.ReplyVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SolutionCommentServiceImpl implements SolutionCommentService {

	@Resource
	private CommentDao commentDao;
	@Resource
	private ReplyDao replyDao;
	@Resource
	private SolutionCommentDao solutionCommentDao;
	@Resource
	private UserDao userDao;
	private Map<String, Object> parameters=new HashMap<String, Object>();
	
	@Override
	public List<CommentVo> queryAllComment(Integer solutionId) {
		parameters.clear();
		parameters.put("solutionId", solutionId);
		List<SolutionComment> solutionCommentList=solutionCommentDao.querySolutionComment(parameters);
		List<CommentVo> commentList=new ArrayList<CommentVo>();
		for (SolutionComment solutionComment : solutionCommentList) {
			parameters.clear();
			parameters.put("commentId", solutionComment.getCommentId());
			List<CommentVo> commentListTemp=commentDao.queryComment(parameters);
			CommentVo comment=new CommentVo();
			if(commentListTemp.size()!=0) {
				comment=commentListTemp.get(0);
			}
			List<ReplyVo> replyList=replyDao.queryReply(parameters);
			if(replyList.size()!=0) {
				for (ReplyVo reply : replyList) {
					parameters.clear();
					parameters.put("userId", reply.getReplyUserId());
					reply.setReplyUserName(userDao.queryUser(parameters).get(0).getUserName());
				}
			}
			comment.setReplyList(replyList);
			commentList.add(comment);
		}
		return commentList;
	}

	@Override
	public void addComment(Comment comment, Integer solutionId) {
		//添加到t_comment
		commentDao.addComment(comment);
		//添加到t_solutioncomment
		parameters.clear();
		parameters.put("commentId", comment.getCommentId());
		parameters.put("solutionId", solutionId);
		solutionCommentDao.addSolutionComment(parameters);
	}

	@Override
	public void addReply(Reply reply) {
		parameters.clear();
		parameters.put("commentId", reply.getCommentId());
		parameters.put("userId", reply.getUserId());
		parameters.put("replyUserId", reply.getReplyUserId());
		parameters.put("replyContent", reply.getReplyContent());
		parameters.put("replyDate", DateUtil.getDateTime());
		replyDao.addReply(parameters);
	}

	@Override
	public Integer getCommentCount(Integer solutionId) {
		return queryAllComment(solutionId).size();
	}

}
